package com.example.demo.zaqizabatest.多线程相关;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName 信号量
 * @Author lys4134
 * @Date 2021/09/06 14:12:54
 * @Description 信号量
 * @Version 1.0
 **/
@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public class SemaphoreDemo implements Callable {
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    Lock readLock = readWriteLock.readLock();
    Lock writeLock = readWriteLock.writeLock();
    Semaphore semaphore = new Semaphore(1);
    volatile static String str = "qwer-";

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        SemaphoreDemo td = new SemaphoreDemo();

        //1.执行 Callable 方式，需要 FutureTask 实现类的支持，用于接收运算结果。
        FutureTask<String> result = new FutureTask<>(td);
        FutureTask<String> result2 = new FutureTask<>(td);
        new Thread(result, "asdf").start();
        new Thread(result2,"zxcv").start();
        System.out.println(result.get());
        System.out.println(result2.get());
    }

    @Override
    public Object call() throws Exception {
        String name = Thread.currentThread().getName();
        try {
            semaphore.acquire();
            str += name;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            semaphore.release();
            //noinspection AlibabaAvoidReturnInFinally
            return str;
        }
    }
}
